<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    /**
     * 回调
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no']; //订单号
                if(strpos($num, 'BG') !== false){
                    $num_type = 1; // 礼包订单
                }elseif (strpos($num, 'BZ') !== false){
                    $num_type = 2; // 赠品订单
                }elseif (strpos($num, 'KC') !== false){
                    $num_type = 3; // 课程订单
                }elseif (strpos($num, 'SK') !== false){
                    $num_type = 4; // 收款订单
                }elseif (strpos($num, 'PB') !== false){
                    $num_type = 5; // 私人订制套餐购买订单
                }elseif (strpos($num, 'TH') !== false){
                    $num_type = 6; // 特惠商场礼包订单
                }

                if($num_type == 1){
                    // 礼包订单回调
                    $order = Db::table('up_bo_orderg')->where('bog_number', $num)
                        ->join('up_bo_giftbag', 'bog_gift_id = gift_id', 'LEFT')
                        ->field('bog_id, bog_status, gift_indate, bog_user_id, bog_gift_id, 
                        bog_total_price, bog_invite, gift_is_zy, bog_is_pay')
                        ->find();

                    $limit = $order['gift_indate'] - 2;
                    $indate = date('Y-m', strtotime("last day of +{$limit} months"));
                    if($order['bog_is_pay'] == 1){
                        $user = Db::table('up_u_user')->where('user_id', $order['bog_user_id'])
                            ->field('user_giftbag_invite_other, user_username, user_giftbag_level, 
                            user_rule, user_bo_role, user_giftbag_date')
                            ->find();

                        $up_user = Db::table('up_u_user')
                            ->where('user_invite', $order['bog_invite'])
                            ->where('user_invite', '<>', '0')
                            ->field('user_id, user_giftbag_balance, user_is_giftbag, user_giftbag_level, 
                            user_rule, user_bo_role')
                            ->find();

                        Db::startTrans();
                        try{
                            /**
                             * 如果有上级，并且上级购买过礼包，则上级可以获取相应的奖励
                             * 1.上级服务费   2.入积分明细
                             */
                            if(($up_user && $up_user['user_giftbag_level'] != 1) || $order['bog_invite'] == 'djl9988'){
                                // 服务费金额
                                $fy = Db::table('up_bo_giftbag')->where('gift_id', $order['bog_gift_id'])->value('gift_fy');
                                $fy_balance = $order['bog_total_price'] * $fy / 100;
                                // 上级分佣
                                Db::table('up_u_user')
                                    ->update([
                                        'user_id' => $up_user['user_id'],
                                        'user_giftbag_balance' => $fy_balance + $up_user['user_giftbag_balance']
                                    ]);
                                // 服务费明细
                                $desc = $user['user_username'] . '-购买礼包服务费';
                                insertBoGiftGagInte($up_user['user_id'], $order['bog_user_id'], 1, $desc, $fy_balance, $up_user['user_giftbag_balance']);
                            }

                            // 增加销量
                            Db::table('up_bo_giftbag')->where('gift_id', $order['bog_gift_id'])->setInc('gift_sale_number');

                            // 修改用户信息
                            $update_user = [
                                'user_id' => $order['bog_user_id'],
                                'user_update_time' => date('Y-m-d H:i:s'),
                                'user_is_giftbag' => 2
                            ];
                            if($order['gift_is_zy'] == 2){ // 非自由创业者
                                if($user['user_giftbag_level'] == 1){ // 普通用户
                                    $update_user['user_giftbag_level'] = 2;
                                }
                            }else{ // 自由创业者
                                if($user['user_giftbag_level'] != 3){
                                    $update_user['user_giftbag_level'] = 3;
                                }
                                if($user['user_bo_role'] == 1){
                                    $update_user['user_bo_role'] = 2;
                                }
                                if($user['user_rule'] == '1'){
                                    $update_user['user_rule'] = '3';
                                }elseif ($user['user_rule'] == '2'){
                                    $update_user['user_rule'] = '2,3';
                                }
                            }

                            if(!$user['user_giftbag_invite_other']){
                                $update_user['user_giftbag_invite_other'] = $order['bog_invite'];
                            }
                            if(!$user['user_giftbag_date']){
                                $update_user['user_giftbag_date'] = date('Y-m-d');
                            }
                            Db::table('up_u_user')->update($update_user);

                            // 修改上级用户身份，上级推广20个丽人礼包，可直接升为自由创业者
                            if($up_user['user_giftbag_level'] == 2){
                                $count = Db::table('up_bo_orderg')
                                    ->join('up_bo_giftbag', 'gift_id = bog_gift_id', 'LEFT')
                                    ->where('bog_up_user_id', $up_user['user_id'])
                                    ->where('gift_is_zy', 2)
                                    ->where('bog_is_pay', 2)
                                    ->count();
                                if($count == 19){
                                    $update_up = [
                                        'user_id' => $up_user['user_id'],
                                        'user_update_time' => date('Y-m-d H:i:s'),
                                    ];
                                    if($up_user['user_giftbag_level'] != 3){
                                        $update_up['user_giftbag_level'] = 3;
                                    }
                                    if($up_user['user_bo_role'] == 1){
                                        $update_up['user_bo_role'] = 2;
                                    }
                                    if($up_user['user_rule'] == '1'){
                                        $update_up['user_rule'] = '3';
                                    }elseif ($up_user['user_rule'] == '2'){
                                        $update_up['user_rule'] = '2,3';
                                    }
                                    Db::table('up_u_user')->update($update_up);
                                }
                            }

                            // 修改订单信息
                            Db::table('up_bo_orderg')->update([
                                'bog_id' => $order['bog_id'],
                                'bog_is_pay' => 2,
                                'bog_status' => 2,
                                'bog_pay_month' => date('Y-m'),
                                'bog_indate' => $indate,
                                'bog_indate_month' => $order['gift_indate'] - 1,
                                'bog_zeng_number' => $order['gift_indate'] - 1,
                                'bog_pay_time' => date('Y-m-d H:i:s'),
                                'bog_up_user_id' => $up_user['user_id']
                            ]);

                            Db::commit();
                            return 'success';
                        }catch (\Exception $e){
                            Db::rollback();
                            return 'error';
                        }
                    }else{
                        return 'success';
                    }
                }elseif($num_type == 2){
                    // 赠品订单回调
                    $order = Db::table('up_bo_orderz')->where('boz_number', $num)
                        ->field('boz_id, boz_status, boz_order_id, boz_no, boz_get_type, boz_user_id, boz_is_pay')->find();
                    if($order['boz_is_pay'] == 1){
                        $update_zeng = [
                            'boz_id' => $order['boz_id'],
                            'boz_is_pay' => 2,
                            'boz_status' => 2,
                            'boz_pay_time' => date('Y-m-d H:i:s'),
                            'boz_get_month' => date('Y-m')
                        ];

                        $alreadyGet = Db::table('up_bo_orderz')
                            ->where(['boz_order_id' => $order['boz_order_id'], 'boz_is_pay' => 2])
                            ->sum('boz_no');
                        if($alreadyGet + $order['boz_no'] == 11){
                            $update_zeng['boz_eleven'] = '已领11盒面膜';
                        }

                        $giftbag_order = Db::table('up_bo_orderg')
                            ->join('up_u_user', 'user_id = bog_user_id', 'LEFT')
                            ->where('bog_id', $order['boz_order_id'])
                            ->field('user_zeng_get_type, user_id')
                            ->find();

                        Db::startTrans();
                        try{
                            // 更新面膜订单信息
                            Db::table('up_bo_orderz')->update($update_zeng);

                            // 减剩余面膜数量
                            Db::table('up_bo_orderg')->where('bog_id', $order['boz_order_id'])->setDec('bog_zeng_number', $order['boz_no']);

                            // 确定用户面膜可领取的渠道
                            if($giftbag_order['user_zeng_get_type'] == 0){
                                Db::table('up_u_user')->where('user_id', $giftbag_order['user_id'])->setField('user_zeng_get_type', $order['boz_get_type']);
                            }

                            // 日志
                            insertGiftbagLog($order['boz_order_id'], '用户领取面膜扣除', 0, $order['boz_no']);

                            Db::commit();
                            return 'success';
                        }catch (\Exception $e){
                            Db::rollback();
                            return 'error';
                        }
                    }else{
                        return 'success';
                    }
                }elseif($num_type == 3){
                    // 课程订单回调
                    $order = Db::table('up_class_order')->where('co_number', $num)
                        ->field('co_user_id, co_class_id, co_total_price, co_number, co_is_pay, co_id')
                        ->find();

                    if($order['co_is_pay'] == 1){
                        $class = Db::table('up_class')->where('class_id', $order['co_class_id'])
                            ->field('class_is_forever, class_valid_date')
                            ->find();
                        // 是否已经在报名表中，如果不在插入我报名的课程表&增加课程报名人数，如果在，就更新有效时间
                        $have_apply = Db::table('up_class_apply')
                            ->where(['c_apply_user_id' => $order['co_user_id'], 'c_apply_class_id' => $order['co_class_id']])
                            ->field('c_apply_id, c_apply_class_forever')
                            ->find();
                        if($class['class_is_forever'] == 1){
                            $valid_date = date('Y-m-d', strtotime("+{$class['class_valid_date']}days"));
                        }else{
//                            $valid_date = 0;
                            $valid_date = '';
                        }

                        Db::startTrans();
                        try{
                            if($have_apply){
                                $update_apply = [
                                    'c_apply_class_forever' => $class['class_is_forever'],
                                    'c_apply_update_time' => date('Y-m-d H:i:s'),
                                    'c_apply_valid' => $valid_date
                                ];
                                // 更新有效期
                                Db::table('up_class_apply')->where('c_apply_id', $have_apply['c_apply_id'])->update($update_apply);
                            }else{
                                // 插入报名表
                                $apply = [
                                    'c_apply_user_id' => $order['co_user_id'],
                                    'c_apply_class_id' => $order['co_class_id'],
                                    'c_apply_class_forever' => $class['class_is_forever'],
                                    'c_apply_valid' => $valid_date,
                                    'c_apply_time' => date('Y-m-d H:i:s')
                                ];
                                Db::table('up_class_apply')->insert($apply);

                                // 更新报名人数
                                Db::table('up_class')->where('class_id', $order['co_class_id'])->setInc('class_apply_number');
                            }

                            Db::table('up_class_order')
                                ->update([
                                    'co_id' => $order['co_id'],
                                    'co_is_pay' => 2,
                                    'co_pay_time' => date('Y-m-d H:i:s')
                                ]);

                            Db::commit();
                            return 'success';
                        }catch (\Exception $e){
                            Db::rollback();
                            return 'error';
                        }
                    }else{
                        return 'success';
                    }
                }elseif ($num_type == 4){
                    // TODO:收款订单回调，收款目前只做了微信，没有做支付宝
                }elseif ($num_type == 5){
                    $order = Db::table('up_private_buy_order')
                        ->join('up_u_user', 'user_id = order_user_id', 'LEFT')
                        ->where('order_no', $num)
                        ->field([
                            'order_user_id',
                            'order_ps_id',
                            'order_number',
                            'order_status',
                            'order_type',
                            'order_id',
                            'user_bo_role',
                            'user_up_tz_code',
                            'user_up_up_tz_code',
                            'user_real_name',
                            'order_total_price',
                            'user_qu',
                            'user_shi',
                            'user_sheng'
                        ])
                        ->find();

                    if($order['order_status'] == 1){
                        $hasStock = Db::table('up_private_stock')
                            ->where(['stock_user_id' => $order['order_user_id'], 'stock_ps_id' => $order['order_ps_id']])
                            ->find();
                        Db::startTrans();
                        try{
                            // 库存
                            if($hasStock){
                                Db::table('up_private_stock')
                                    ->where('stock_id', $hasStock['stock_id'])
                                    ->inc('stock_number', $order['order_number'])
                                    ->update();
                            }else{
                                Db::table('up_private_stock')
                                    ->insert([
                                        'stock_user_id' => $order['order_user_id'],
                                        'stock_ps_id' => $order['order_ps_id'],
                                        'stock_number' => $order['order_number']
                                    ]);
                            }

                            // 订单状态
                            Db::table('up_private_buy_order')
                                ->update([
                                    'order_id' => $order['order_id'],
                                    'order_status' => 2,
                                    'order_pay_time' => date('Y-m-d H:i:s')
                                ]);

                            // 加盟商提成
                            if($order['order_type'] == 1){
                                //*************************  团长分佣   start ****************************//
                                // 2.本团/上级分佣
                                $upHuoFyUser = $this->getBoUserSystemHuo(1, $order['user_bo_role'], $order['user_up_tz_code'], $order['user_up_up_tz_code']);
                                if($upHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy1 = $huo_balance * $upHuoFyUser['ratio'] / 100; // 分佣金额
                                    $huoTzFy1 = $order['order_total_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                                    $descFyHuo1 = $order['user_real_name'] . '私人订制套餐-佣金';

                                    $this->insertBoFy($upHuoFyUser['tz_user_id'], $order['order_user_id'], $upHuoFyUser['should_user_id'], $upHuoFyUser['freeze_user_id'], 1, $descFyHuo1, 1, $huoTzFy1, $upHuoFyUser['bo_balance'], 0, $upHuoFyUser['hf'], 1, $upHuoFyUser['freeze_name']);

                                    Db::table('up_u_user')
                                        ->where('user_id', $upHuoFyUser['tz_user_id'])
                                        ->inc('user_bo_fy_balance', $huoTzFy1)
                                        ->inc('user_bo_total_fy_balance', $huoTzFy1)
                                        ->update();
                                }

                                // 3.上级/上上级团队长分佣
                                $upUpHuoFyUser = $this->getBoUserSystemHuo(2, $order['user_bo_role'], $order['user_up_tz_code'], $order['user_up_up_tz_code']);
                                if($upUpHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy2 = $huo_balance * $upUpHuoFyUser['ratio'] / 100; // 分佣金额
                                    $huoTzFy2 = $order['order_total_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                                    $descFyHuo2 = $order['user_real_name'] . '私人订制套餐-佣金';

                                    $this->insertBoFy($upUpHuoFyUser['tz_user_id'], $order['order_user_id'], $upUpHuoFyUser['should_user_id'], $upUpHuoFyUser['freeze_user_id'], 1, $descFyHuo2, 1, $huoTzFy2, $upUpHuoFyUser['bo_balance'], 0, $upUpHuoFyUser['hf'], 1, $upUpHuoFyUser['freeze_name']);

                                    Db::table('up_u_user')
                                        ->where('user_id', $upUpHuoFyUser['tz_user_id'])
                                        ->inc('user_bo_fy_balance', $huoTzFy2)
                                        ->inc('user_bo_total_fy_balance', $huoTzFy2)
                                        ->update();
                                }
                                //*************************  团长分佣   end ****************************//

                                //*************************  代理分佣   start ****************************//
                                // 4.县代管理费
                                $quFyUser = $this->getDaiLiFy(3, $order['user_qu']);
                                if($quFyUser['should_user_id'] != 0){
//                                $huoDlFy3 = $huo_balance * $quFyUser['ratio'] / 100; // 分佣金额
                                    $huoDlFy3 = $order['order_total_price'] * config('default_qu_ratio') / 100; // 分佣金额
                                    $descFyHuo3_dl = $order['user_real_name'] . '私人订制套餐-县管理费';

                                    $this->insertBoFy($quFyUser['fy_user_id'], $order['order_user_id'], $quFyUser['should_user_id'], 0, 1, $descFyHuo3_dl, 1, $huoDlFy3, $quFyUser['bo_balance'], 0, $quFyUser['hf'], 2, $quFyUser['freeze_name']);

                                    Db::table('up_u_user')
                                        ->where('user_id', $quFyUser['fy_user_id'])
                                        ->inc('user_bo_fy_balance', $huoDlFy3)
                                        ->inc('user_bo_total_fy_balance', $huoDlFy3)
                                        ->update();
                                }

                                // 5.市代管理费
                                $shiFyUser = $this->getDaiLiFy(2, $order['user_shi']);
                                if($shiFyUser['should_user_id'] != 0){
//                                $huoDlFy2 = $huo_balance * $shiFyUser['ratio'] / 100; // 分佣金额
                                    $huoDlFy2 = $order['order_total_price'] * config('default_shi_ratio') / 100; // 分佣金额
                                    $descFyHuo2_dl = $order['user_real_name'] . '私人订制套餐-市管理费';

                                    $this->insertBoFy($shiFyUser['fy_user_id'], $order['order_user_id'], $shiFyUser['should_user_id'], 0, 1, $descFyHuo2_dl, 1, $huoDlFy2, $shiFyUser['bo_balance'], 0, $shiFyUser['hf'], 3, $shiFyUser['freeze_name']);

                                    Db::table('up_u_user')
                                        ->where('user_id', $shiFyUser['fy_user_id'])
                                        ->inc('user_bo_fy_balance', $huoDlFy2)
                                        ->inc('user_bo_total_fy_balance', $huoDlFy2)
                                        ->update();
                                }

                                // 6.省代管理费
                                $shengFyUser = $this->getDaiLiFy(1, $order['user_sheng']);
                                if($shengFyUser['should_user_id'] != 0){
//                                $huoDlFy1 = $huo_balance * $shengFyUser['ratio'] / 100; // 分佣金额
                                    $huoDlFy1 = $order['order_total_price'] * config('default_sheng_ratio') / 100; // 分佣金额
                                    $descFyHuo1_dl = $order['user_real_name'] . '私人订制套餐-省管理费';

                                    $this->insertBoFy($shengFyUser['fy_user_id'], $order['order_user_id'], $shengFyUser['should_user_id'], 0, 1, $descFyHuo1_dl, 1, $huoDlFy1, $shengFyUser['bo_balance'], 0, $shengFyUser['hf'], 4, $shengFyUser['freeze_name']);

                                    Db::table('up_u_user')
                                        ->where('user_id', $shengFyUser['fy_user_id'])
                                        ->inc('user_bo_fy_balance', $huoDlFy1)
                                        ->inc('user_bo_total_fy_balance', $huoDlFy1)
                                        ->update();
                                }
                                //*************************  代理分佣   end ****************************//
                            }

                            Db::commit();
                            return 'success';
                        }catch (\Exception $e){
                            Db::rollback();
                            return 'error';
                        }
                    }else{
                        return 'success';
                    }

                }elseif ($num_type == 6){
                    $order = Db::table('up_order')->where('order_number', $num)->field('order_id, order_is_pay')->find();
                    if($order['order_is_pay'] == 1){
                        $res = Db::table('up_order')
                            ->where('order_id', $order['order_id'])
                            ->update([
                                'order_is_pay' => 2,
                                'order_status' => 2,
                                'order_pay_time' => date('Y-m-d H:i:s')
                            ]);
                        if($res){
                            return 'success';
                        }else{
                            return 'error';
                        }
                    }else{
                        return 'success';
                    }
                }

            }
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = config('ali.alipayrsaPublicKey');
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }

    /**
     * 回调信息写入文件----用于查看返回信息
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }
}